<?php

namespace admin\controllers;

use app\helpers\AppHelper;
use app\helpers\HighChartHelper;
use app\models\ar\StatisticAr;
use app\models\Statistic;
use admin\components\BaseAuthController;
use yii\helpers\Json;
use yii\web\View;

class StatisticController extends BaseAuthController {

    public $name = '数据统计';

    public function actionIndex() {
        $defaultType = current(array_keys(StatisticAr::$STATISTICS_TYPES));

        $isExport = $this->get('export');
        $type = $this->get('type', $defaultType);
        $begDate = $this->get('begDate', date('Y-m-d', strtotime('-7 day')));
        $endDate = $this->get('endDate', date('Y-m-d', strtotime('-1 day')));

        $beg_time = strtotime($begDate);
        $end_time = strtotime($endDate) + 86400 - 1;

        $name = StatisticAr::getStatisticsTitleByType($type);

        $model = new Statistic();
        $model->where = ['and', ['type' => $type], ['between', 'ts', $beg_time, $end_time]];
        if ($isExport) {
            $models = Statistic::find()->where($model->where)->asArray()->all();
            AppHelper::export($models, $name);
            exit;
        }

        $dataProvider = $model->search();

        $highChart = HighChartHelper::format($dataProvider->getModels(), $name);
        $this->view->registerJs("var highcharts = " . Json::encode($highChart) . ';', View::POS_HEAD);
        return $this->render(compact('dataProvider', 'type', 'name', 'begDate', 'endDate', 'highChart'));
    }
}
